import sys

from backends.support import ResourceCategory, ResourceRawHTML

from backends.schoolloop import SchoolloopBackend
from backends.haiku import HaikuBackend
from backends.dummy import DummyBackend

backends = [DummyBackend, SchoolloopBackend, HaikuBackend]
backend = { x.__name__ : x for x in backends } [sys.argv[1]] ()

from http.client import HTTPConnection
import logging
HTTPConnection.debuglevel = 1
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True

def authenticate():
    config = {
        "Email": sys.argv[2],
        "Username": sys.argv[2],
        "Password": sys.argv[3],
        "School": sys.argv[4]
    }

    if backend.login(config):
        backend.authenticated = True
    else:
        print("Bad credentials")
        sys.exit(1)

def dump_resources(rsrc, count):
    if isinstance(rsrc, ResourceCategory):
        print(("  " * count) + rsrc.name)

        for child in rsrc.children:
            dump_resources(child, count + 1)

        if rsrc.name == "Welcome":
            for child in rsrc.contents:
                dump_resources(child, count + 1)
    elif isinstance(rsrc, ResourceRawHTML):
        print(("  " * count) + rsrc.name + ": " + rsrc.html)
    else:
        print(("  " * count) + rsrc.name + " (" + type(rsrc).__name__ + ")")

authenticate()

for course in backend.courses:
    print(course.title + " by " + course.teacher + " (ID " + course.id + ")")

    try:
        print("Course grade: " + str(course.grade_summary))

        if course.title == "TODO: Don't waste bandwidth":
            for category in course.grades:
                print(category.name + ": " + str(round(category.mean * 100)) + "%")

                for grade in category.grades:
                    print(".. " + grade.name + ": " + str(round(grade.grade * 100)) + "%")
    except AttributeError:
        print("Backend does not implement grades")

    try:
        dump_resources(course.resources, 0)
    except AttributeError:
        print("Backend does not implement resources")

    try:
        for task in course.tasks:
            print("- " + task.name)
    except AttributeError:
        print("Backend does not implement tasks")

    print("----")

